package com.time.workshop.ui;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.time.workshop.API;
import com.time.workshop.App;
import com.time.workshop.BaseConstant;
import com.time.workshop.R;
import com.time.workshop.SuperActivity;
import com.time.workshop.injector.Injector;
import com.time.workshop.injector.V;
import com.time.workshop.utils.ActionSheetDialog;
import com.time.workshop.utils.ActionSheetDialog.OnSheetItemClickListener;
import com.time.workshop.utils.ActionSheetDialog.SheetItemColor;
import com.time.workshop.utils.CommonUtils;
import com.time.workshop.utils.ImageUtil;
import com.time.workshop.utils.NewToast;
import com.time.workshop.utils.PreferenceUtil;

/**
 * 发布需求页面
 */
public class AddTaskActivity extends SuperActivity
{

	@V
	private ImageView img_add_task_photo;
	@V
	private EditText tv_add_task_timeTextView, et_add_task_content, et_add_task_title, add_task_addressEditText, add_task_moneyEditText, add_task_usernameEditText;
	@V
	private TextView tv_add_task_commitOrderTextView;
	@V
	private RelativeLayout add_task_time_Layout;
	@V
	private Button add_task_titlebar_left_btn;

	private static final int IMAGE_REQUEST_CODE = 0; // 相册
	private static final int CAMERA_REQUEST_CODE = 1; // 拍照
	private static final int RESULT_REQUEST_CODE = 2; //

	@Override
	protected void onCreate(Bundle bundle)
	{
		super.onCreate(bundle);
		setContentView(R.layout.activity_addtask);
		setView();
	}

	private void setView()
	{
		Injector.getInstance().inject(this);
		img_add_task_photo.setOnClickListener(this);
		// add_task_time_Layout.setOnClickListener(this);
		tv_add_task_commitOrderTextView.setOnClickListener(this);
		add_task_titlebar_left_btn.setOnClickListener(this);
	}

	@Override
	public void onClick(View view)
	{
		super.onClick(view);
		switch (view.getId())
		{
		case R.id.img_add_task_photo:

			showImageDialog();

			break;
		case R.id.add_task_time_Layout:
			dateTimePickerDialog();
			break;
		case R.id.tv_add_task_commitOrderTextView:

			publishTask();

			break;
		case R.id.add_task_titlebar_left_btn:
			back();
			break;

		default:
			break;
		}
	}

	/**
	 * 弹出选择相片的dialog
	 */
	private void showImageDialog()
	{

		new ActionSheetDialog(AddTaskActivity.this).builder().setCancelable(true).setCanceledOnTouchOutside(true).addSheetItem("拍照", SheetItemColor.Blue, new OnSheetItemClickListener()
		{
			@Override
			public void onClick(int which)
			{
				Intent in = new Intent(AddTaskActivity.this, CameraActivity.class);
				startActivityForResult(in, 1);
			}
		}).addSheetItem("相册", SheetItemColor.Blue, new OnSheetItemClickListener()
		{
			@Override
			public void onClick(int which)
			{
				Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				// i.setPackage("xxxx");// xxxx是具体报名，系统默认的一般是com.android.xx
				startActivityForResult(i, IMAGE_REQUEST_CODE);
			}
		}).show();

	}

	/**
	 * 发布需求
	 */
	private void publishTask()
	{
		if (invalidateText(et_add_task_content, R.string.please_input_task_content) || invalidateText(et_add_task_title, R.string.please_input_task_title) || invalidateText(tv_add_task_timeTextView, R.string.please_input_task_time) || invalidateText(add_task_addressEditText, R.string.please_input_task_address) || invalidateText(add_task_moneyEditText, R.string.please_input_task_price))
		{
			return;
		}
		if ("".equals(CommonUtils.isnull(mImagePath)))
		{
			NewToast.makeText(this, getResources().getString(R.string.please_input_task_image));
			return;
		}
		if ("".equals(CommonUtils.isnull(getText(add_task_usernameEditText))))
		{
			NewToast.makeText(this, getResources().getString(R.string.please_input_task_username));
			return;
		}

		if (!CommonUtils.isNetworkConnected(getApplicationContext()))
		{
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.M000));
			return;
		}

		showLoadingDialog();

		FinalHttp fh = new FinalHttp();
		AjaxParams params = new AjaxParams();
		try
		{
			params.put("image", new File(mImagePath));
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}

		params.put("token", PreferenceUtil.getString(this, BaseConstant.PREF_TOKE_STRING));
		params.put("TITLE", getText(et_add_task_title));
		params.put("USERNAME", getText(add_task_usernameEditText));
		params.put("NEED_INFO", getText(et_add_task_content));
		params.put("NEED_TIME", getText(tv_add_task_timeTextView));
		params.put("NEED_ADDRESS", getText(add_task_addressEditText));
		params.put("PRICE", getText(add_task_moneyEditText));

		fh.post(API.add_task, params, new AjaxCallBack<Object>()
		{
			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg)
			{
				super.onFailure(t, errorNo, strMsg);
				App.showLog(strMsg);
				NewToast.makeText(getApplicationContext(), "发布失败");
				dismissLoadingDialog();
			}

			@Override
			public void onSuccess(Object t)
			{
				super.onSuccess(t);
				App.showLog(t.toString());
				dismissLoadingDialog();
				try
				{
					JSONObject jsonObject = new JSONObject(t.toString());
					if (jsonObject.getBoolean("success"))
					{
						App.showShortToast(jsonObject.getString("message"));
						String ID = jsonObject.getString("result");
						Intent in = new Intent(AddTaskActivity.this, TimeHallDetailActivity.class);
						in.putExtra("ID", ID);
						startActivity(in, true);
						finish();
					} else
					{
						App.showShortToast(jsonObject.getString("message"));
					}

				} catch (JSONException e)
				{
					e.printStackTrace();
				}

			}

		});

	}

	private DatePicker datePicker;
	private TimePicker timePicker;
	private AlertDialog dialog;
	public Calendar time = Calendar.getInstance(Locale.CHINA);

	// 选择时间
	private AlertDialog dateTimePickerDialog()
	{
		LinearLayout dateTimeLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.date_time_picker, null);
		datePicker = (DatePicker) dateTimeLayout.findViewById(R.id.DatePicker);
		timePicker = (TimePicker) dateTimeLayout.findViewById(R.id.TimePicker);
		timePicker.setIs24HourView(true);

		OnTimeChangedListener timeListener = new OnTimeChangedListener()
		{
			@Override
			public void onTimeChanged(TimePicker view, int hourOfDay, int minute)
			{
				time.set(Calendar.HOUR_OF_DAY, hourOfDay);
				time.set(Calendar.MINUTE, minute);

			}
		};

		timePicker.setOnTimeChangedListener(timeListener);
		OnDateChangedListener dateListener = new OnDateChangedListener()
		{

			@Override
			public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
			{
				time.set(Calendar.YEAR, year);
				time.set(Calendar.MONTH, monthOfYear);
				time.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			}
		};

		datePicker.init(time.get(Calendar.YEAR), time.get(Calendar.MONTH), time.get(Calendar.DAY_OF_MONTH), dateListener);
		timePicker.setCurrentHour(time.get(Calendar.HOUR_OF_DAY));
		timePicker.setCurrentMinute(time.get(Calendar.MINUTE));

		dialog = new AlertDialog.Builder(this).setTitle("设置日期时间").setView(dateTimeLayout).setPositiveButton("确定", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{

				time.set(Calendar.YEAR, datePicker.getYear());
				time.set(Calendar.MONTH, datePicker.getMonth());
				time.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
				time.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
				time.set(Calendar.MINUTE, timePicker.getCurrentMinute());
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				tv_add_task_timeTextView.setText(format.format(time.getTime()));
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{

			}
		}).show();
		return dialog;
	}

	private String path = "";
	private Uri imageUri;
	private String mImagePath = "";

	/** 调用相机拍照 */
	public void photo()
	{

		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		String state = Environment.getExternalStorageState();
		if (!state.equals(Environment.MEDIA_MOUNTED))
		{
			App.showShortToast("没找到存储卡");
			return;
		}

		File dir = new File(Environment.getExternalStorageDirectory() + "/Workshop");
		if (!dir.exists())
		{
			dir.mkdir();
		}

		File file = new File(Environment.getExternalStorageDirectory() + "/Workshop/", String.valueOf(System.currentTimeMillis()) + ".jpg");
		path = file.getPath();
		App.showLog("path===" + path);
		imageUri = Uri.fromFile(file);
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(openCameraIntent, CAMERA_REQUEST_CODE);
	}

	/**
	 * 图片压缩方法实现
	 * 
	 * @param srcPath
	 * @returnc
	 */
	private Bitmap getimage(String srcPath)
	{
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);

		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		int hh = 440;// 这里设置高度为800f
		int ww = 640;// 这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww)
		{// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh)
		{// 如果高度高的话根据高度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
	}

	/**
	 * 质量压缩
	 * 
	 * @param image
	 * @return
	 */
	private Bitmap compressImage(Bitmap image)
	{

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while (baos.toByteArray().length / 1024 > 100)
		{ // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset(); // 重置baos即清空baos
			options -= 10; // 每次都减少10
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中

		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		try
		{
			File picture = new File(CommonUtils.getDiskCacheDir(context, "imgs"), DateFormat.format("yyyyMMddhhmmss", new Date()).toString() + ".jpg");
			mImagePath = picture.getAbsolutePath();
			FileOutputStream out = new FileOutputStream(mImagePath);
			bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
			long fileLen = picture.length();
			System.out.println("图片大小：" + fileLen + ";" + "旋转大小：" + 102400);
			if (fileLen > 1024 * 100 * 5)
			{
				bitmap = ImageUtil.rotaingBitmap(90, bitmap);
			}
			ImageUtil.saveBitmap(bitmap, picture);
			// img_add_task_photo.setImageBitmap(bitmap);
			ImageLoader.getInstance().displayImage("file:///" + mImagePath, img_add_task_photo, getDisplayOption());
		} catch (Exception e)
		{

		}
		return bitmap;
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri)
	{

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 16);
		intent.putExtra("aspectY", 11);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 640);
		intent.putExtra("outputY", 440);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 2);
	}

	/**
	 * 保存裁剪之后的图片数据
	 * 
	 * @param picdata
	 */
	@SuppressWarnings("deprecation")
	private void getImageToView(Intent data)
	{
		Bundle extras = data.getExtras();
		if (extras != null)
		{
			Bitmap photo = extras.getParcelable("data");
			final Drawable drawable = new BitmapDrawable(photo);
			// 显示图片
			img_add_task_photo.setImageDrawable(drawable);

			// 此处为上传代码------------------------
			// 为了测试将代码放于此处，到时应该和数据上传发在一起

			try
			{
				File picture = new File(CommonUtils.getDiskCacheDir(context, "imgs"), "taskimage.jpg");
				FileOutputStream out = new FileOutputStream(picture.getAbsolutePath());
				photo.compress(Bitmap.CompressFormat.PNG, 90, out); //

				mImagePath = picture.getAbsolutePath();

				// showLoadingDialog();
				// FinalHttp fh = new FinalHttp();
				// AjaxParams params = new AjaxParams();
				// params.put("image", new
				// File(Environment.getExternalStorageDirectory() +
				// "/Workshop/taskimage.jpg"));
				// params.put("token", PreferenceUtil.getString(this,
				// BaseConstant.PREF_TOKE_STRING));
				//
				// fh.post(API.user_face_img, params, new AjaxCallBack<Object>()
				// {
				//
				// @Override
				// public void onFailure(Throwable t, int errorNo, String
				// strMsg)
				// {
				// super.onFailure(t, errorNo, strMsg);
				// dismissLoadingDialog();
				// App.showLog("strMsg==" + strMsg);
				// }
				//
				// @Override
				// public void onSuccess(Object t)
				// {
				// super.onSuccess(t);
				// dismissLoadingDialog();
				// try
				// {
				// JSONObject jsonObject = new JSONObject(t.toString());
				// if (jsonObject.getBoolean("success"))
				// {
				// img_add_task_photo.setImageDrawable(drawable);
				// App.showShortToast(jsonObject.getString("message"));
				// } else
				// {
				// App.showShortToast(jsonObject.getString("message"));
				// }
				//
				// } catch (Exception e)
				// {
				// e.printStackTrace();
				// }
				//
				// }
				//
				// });

			} catch (Exception e)
			{

			}

		}
	}

	/**
	 * 取得图片回传的数据
	 */
	@SuppressWarnings(
	{ "unused", "deprecation" })
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{

		if (resultCode != RESULT_CANCELED)
		{
			ContentResolver resolver = getContentResolver();
			Bitmap bm = null;
			switch (requestCode)
			{

			// 本地图库
			case IMAGE_REQUEST_CODE:

				// startPhotoZoom(data.getData());

				try
				{
					Uri originalUri = data.getData();
					bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);
					String[] proj =
					{ MediaStore.Images.Media.DATA };
					Cursor cursor = managedQuery(originalUri, proj, null, null, null);
					int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					cursor.moveToFirst();
					mImagePath = cursor.getString(column_index);
					if (VERSION.SDK_INT < 14)
					{
						cursor.close();
					}
					// bm = BitmapFactory.decodeFile(mImagePath);
					// ImageUtil.blurImageAmeliorate(bm);
					// 矫正图片旋转角度
					// bm = ImageUtil.getDiskBitmap(mImagePath);
					// 压缩大小
					getimage(mImagePath);

				} catch (Exception e)
				{
					Log.w(TAG, e.toString());
				}
				break;
			case CAMERA_REQUEST_CODE:

				mImagePath = data.getStringExtra("url");
				ImageLoader.getInstance().displayImage("file:///" + mImagePath, img_add_task_photo, getDisplayOption());

				// if (CommonUtils.hasSDCard())
				// {
				// startPhotoZoom(imageUri);
				// // 压缩大小
				// getimage(path);
				// } else
				// {
				// NewToast.makeText(getApplicationContext(), "没找到存储卡");
				// }
				break;
			case RESULT_REQUEST_CODE:
				if (data != null)
				{
					getImageToView(data);
				}
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

}
